package com.eee.machine.utils;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    /**
     * <p> md5</p>
     * <p>Description: 生成固定长度的MD5加密串</p>
     *
     * @param str 需要加密的字符串
     * @return java.lang.String
     * @author mai 2016-12-09
     * @version V1.0.0
     */
    public static String md5(String str) {

        StringBuilder mess = new StringBuilder();
        try {
            //创建md5摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            Charset charset = Charset.forName("UTF-8");
            byte[] bytes = str.getBytes(charset);
            byte[] digest = md.digest(bytes);

            for (byte b : digest) {

                int d = b & 0xff;// 0x000000ff
                String hexString = Integer.toHexString(d);
                if (hexString.length() == 1) {
                    hexString = "0" + hexString;
                }
                mess.append(hexString);

            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return mess.toString();
    }
}
